package own.stu.inter.loadbalance.chooseRule;

import own.stu.inter.loadbalance.ILoadBalancer;
import own.stu.inter.loadbalance.server.ServerInstance;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

// TODO spi rule
public class RandomRule extends AbstractChooseRule {

    public RandomRule(ILoadBalancer lb) {
        super(lb);
    }

    /**
     * 随机
     */
    public ServerInstance choose(Object key) {

        ServerInstance server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<ServerInstance> upList = lb.getActiveServers();
            List<ServerInstance> allList = lb.getAllServers();

            int serverCount = allList.size();
            if (serverCount == 0) {
                return null;
            }

            int index = chooseRandomInt(serverCount);
            server = upList.get(index);

            if (server == null) {
                sleepAWhile(10);
                continue;
            }

            if (server.isAlive()) {
                return server;
            }

            server = null;
            sleepAWhile(10);
        }

        return server;

    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }
}
